﻿/*

The MIT License

Copyright (c) 2010 Cartesian Analytics, Inc. 

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace Pipra.Uom
{
    public abstract class UomFactorAuthorityBase :
        IUomAuthority
    {

        public readonly string Type;
        private readonly Dictionary<IUom, Dictionary<IUom, ConversionFactorEntry>> _lookup;

        protected UomFactorAuthorityBase(string type, UomComparer uomComparer)
            : this(type, uomComparer, null) { }

        protected UomFactorAuthorityBase(string type, Dictionary<IUom, Dictionary<IUom, ConversionFactorEntry>> lookup)
            : this(type, null, lookup) { }

        private UomFactorAuthorityBase(string type, UomComparer uomComparer, Dictionary<IUom, Dictionary<IUom, ConversionFactorEntry>> lookup)
        {
            if (String.IsNullOrEmpty(type))
            {
                throw new ArgumentNullException("type");
            }
            Type = type;
            if (null == lookup)
            {
                _lookup = new Dictionary<IUom, Dictionary<IUom, ConversionFactorEntry>>(uomComparer ?? new UomComparer());
            }
            else
            {
                _lookup = new Dictionary<IUom, Dictionary<IUom, ConversionFactorEntry>>(uomComparer ?? lookup.Comparer);
                foreach (KeyValuePair<IUom, Dictionary<IUom, ConversionFactorEntry>> fromEntry in lookup)
                {
                    foreach (KeyValuePair<IUom, ConversionFactorEntry> toEntry in fromEntry.Value)
                    {
                        SetEntry(fromEntry.Key, toEntry.Key, toEntry.Value);
                    }
                }
            }
        }

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        string IUomAuthority.Type
        {
            get { return Type; }
        }

        protected void SetEntry(IUom from, IUom to, ConversionFactorEntry entry)
        {
            if (null == entry)
            {
                throw new ArgumentNullException("entry");
            }
            if (null == from)
            {
                throw new ArgumentNullException("from");
            }
            if (null == to)
            {
                throw new ArgumentNullException("to");
            }
            if (_lookup.Comparer.Equals(from, to))
            {
                return;
            }
            Dictionary<IUom, ConversionFactorEntry> subLookup;
            if (!_lookup.TryGetValue(from, out subLookup))
            {
                subLookup = new Dictionary<IUom, ConversionFactorEntry>(_lookup.Comparer);
                _lookup.Add(from, subLookup);
            }
            subLookup[to] = entry;
            if (!_lookup.TryGetValue(to, out subLookup))
            {
                subLookup = new Dictionary<IUom, ConversionFactorEntry>(_lookup.Comparer);
                _lookup.Add(to, subLookup);
            }
            ConversionFactorEntry invEntry;
            if (!subLookup.TryGetValue(from, out invEntry) || invEntry.OpCount > entry.OpCount)
            {
                subLookup[from] = ConversionFactorEntry.GetInverted(entry);
            }
        }

        public ConversionFactorEntry GetEntry(IUom from, IUom to)
        {
            Dictionary<IUom, ConversionFactorEntry> toLookup;
            ConversionFactorEntry entry;
            return (
                (_lookup.TryGetValue(from, out toLookup) && toLookup.TryGetValue(to, out entry))
                ? entry
                : null
            );
        }

        public IEnumerable<IUom> Units
        {
            get { return _lookup.Keys; }
        }
        
        public virtual IUom GetUnit(string name)
        {
            UomComparer cmp = Comparer;
            return Units.FirstOrDefault(u => cmp.Equals(u.Name, name));
        }

        public UomComparer Comparer
        {
            get { return _lookup.Comparer as UomComparer; }
        }


        public IEnumerable<IUom> GetMappedUnits(IUom from)
        {
            Dictionary<IUom, ConversionFactorEntry> toLookup;
            return (
                _lookup.TryGetValue(from, out toLookup)
                ? toLookup.Keys
                : Enumerable.Empty<IUom>()
            );
        }

        public IValueConverter GetConverter(IUom from, IUom to)
        {
            ConversionFactorEntry entry = GetEntry(from, to);
            return (
                null == entry
                ? null
                : FactorValueConverter.CreateConverter(Type, from, to, entry)
            );
        }

    }
}
